import {
	tdt
} from "../common/config.js"

/**
 * 将服务添加至地图上
 * @param {Array} 	layers		服务图层
 * @param {Number} 	wkid		空间参考
 * @param {Object} 	Arcgis		Arcgis方法类
 * @returns []	处理后的layers, 可通过viewer.map.addMany(layers) 添加到地图
 */
export const getMapLayers = async ({
	layers = [],
	wkid = 4490,
	res = [],
	Arcgis: {
		SpatialReference,
		TileInfo,
		WebTileLayer,
		MapImageLayer,
		TileLayer,
		FeatureLayer,
	}
}) => {
	return new Promise((resolve, reject) => {
		if (!layers || !Array.isArray(layers)) return res

		//  空间参考
		let spatialReference = new SpatialReference({
			wkid: wkid ? wkid : 4490
		});

		const objMethod = {
			// 天地图
			tianditu: (data) => {
				return new Promise((resolve, reject) => {
					let {
						TDTBaseUrl,
						TdtToken,
						subDomains,
						tdtTileInfo
					} = tdt;
					let {
						service = 'WMTS', layerType = 'img', version = '1.0.0',
							request = 'GetTile',
							tileMatrixSet =
							'w', style = 'default', format = 'tiles', title = "_title",
							visible =
							true,
							opacity = 1,
							id
					} = data;
					//  配置模板url
					let urlTemplate =
						`${tdt.TDTBaseUrl}/${layerType}_${tileMatrixSet}/${service.toLowerCase()}?SERVICE=${service}&REQUEST=${request}&VERSION=${version}&LAYER=${layerType}&STYLE=${style}&TILEMATRIXSET=${tileMatrixSet}&FORMAT=${format}&TILEMATRIX={level}&TILEROW={row}&TILECOL={col}&tk=${tdt.TdtToken}`;
					//  设置天地图切片配置的空间参考
					let bufferTdtTileInfo = JSON.parse(JSON.stringify(tdt.tdtTileInfo));
					bufferTdtTileInfo.spatialReference = spatialReference

					let layerConfig = {
						urlTemplate,
						subDomains: tdt.subDomains,
						title,
						visible,
						opacity,
						spatialReference,
						id
					};
					if (wkid == 4490) {
						layerConfig.tileInfo = new TileInfo(bufferTdtTileInfo)
					}
					let layer = new WebTileLayer(layerConfig);
					resolve(layer)
				})
			},
			// 动态服务图层
			dynamic: (data) => {
				return new Promise((resolve, reject) => {
					let params = {
						...data,
						spatialReference,
					}
					let layer = new MapImageLayer(params);
					resolve(layer)
				})
			},
			// 切片服务
			tile: (data) => {
				return new Promise((resolve, reject) => {
					let params = {
						...data,
						spatialReference,
					}
					let layer = new TileLayer(params);
					resolve(layer)
				})
			},
			// feature 服务
			feature: (data) => {
				return new Promise((resolve, reject) => {
					let params = {
						...data,
						spatialReference,
					}
					let layer = new FeatureLayer(params);
					resolve(layer)
				})
			},
		}

		let a = layers.filter(item => {
			return objMethod[item.serviceType] && objMethod[item.serviceType](item)
		})
		let cc = await Promise.all(a)
		console.log(cc, '======');
		return cc
	})
}